package me.evis.mobile.sms2cal.parser;

import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import me.evis.mobile.sms2cal.model.CalEvent;
import me.evis.mobile.sms2cal.model.SmsData;

import android.util.Log;

public class FlightReminderParser implements SmsParser {
    /** Tag string for debug logs */
    private static final String TAG = "me.evis.mobile.sms2cal.parser.FlightReminderParser";
    
    private static final List<String> possibleSenders = Arrays.asList(new String[] {
            "10086", "10010"
    });
    private static final String matchRegex = 
        "^(?:[^/]+?)(?:/(?:[A-Z]{2}[\\d]{4,})/(?:[\\d]{1,2})月(?:[\\d]{1,2})日/(?:[^/]+?)(?:[\\d]{1,2}):(?:[\\d]{1,2})-(?:[^/]+?)(?:[\\d]{1,2}):(?:[\\d]{1,2})[^/]+?)+/编号(?:\\w+).+$";
    private static final String parseCustomerAndCodeRegex = 
        "^([^/]+?)(?:/(?:[A-Z]{2}[\\d]{4,})/(?:[\\d]{1,2})月(?:[\\d]{1,2})日/(?:[^/]+?)(?:[\\d]{1,2}):(?:[\\d]{1,2})-(?:[^/]+?)(?:[\\d]{1,2}):(?:[\\d]{1,2})[^/]+?)+/编号(\\w+).+$";
    private static final String parseFlightsRegex = 
        "/([A-Z]{2}[\\d]{4,})/([\\d]{1,2})月([\\d]{1,2})日/([^/]+?)([\\d]{1,2}):([\\d]{1,2})-([^/]+?)([\\d]{1,2}):([\\d]{1,2})[^/]+?";
    
    @Override
    public boolean parse(SmsData sms, List<CalEvent> results) {
        // Is parser applicable
        boolean applicable = false;
        if (possibleSenders.contains(sms.from)) {
            Pattern pattern = Pattern.compile(matchRegex, Pattern.CASE_INSENSITIVE);
            Matcher m = pattern.matcher(sms.messageBody);
            if (m.matches()) {
                applicable = true;
            }
        }
        if (!applicable) {
            return false;
        }
        
        // Parse
        Pattern pattern = Pattern.compile(parseCustomerAndCodeRegex, Pattern.CASE_INSENSITIVE);
        Matcher m = pattern.matcher(sms.messageBody);
        String passengerName = "";
        String itineraryId = "";
        
        while (m.find()) {
            passengerName = m.group(1);
            itineraryId = m.group(m.groupCount());
        }
        
        pattern = Pattern.compile(parseFlightsRegex, Pattern.CASE_INSENSITIVE);
        m = pattern.matcher(sms.messageBody);
        while (m.find()) {
            FlightInfo flight = new FlightInfo();
            
            flight.passengerName = passengerName;
            flight.itineraryId = itineraryId;
            flight.flightNumber = m.group(1);
            
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(sms.receiveOn);
            final int dYear = calendar.get(Calendar.YEAR);
            final int dMonth = Integer.valueOf(m.group(2));
            final int dDay = Integer.valueOf(m.group(3));
            final int dHour = Integer.valueOf(m.group(5));
            final int dMinute = Integer.valueOf(m.group(6));
            calendar.clear();
            calendar.set(dYear, dMonth - 1, dDay, dHour, dMinute);
            flight.departureDate = calendar.getTime();
            
            final int aYear = dYear;
            final int aMonth = dMonth;
            final int aDay = dDay;
            final int aHour = Integer.valueOf(m.group(8));
            final int aMinute = Integer.valueOf(m.group(9));
            calendar.clear();
            calendar.set(aYear, aMonth - 1, aDay, aHour, aMinute);
            flight.arrivalDate = calendar.getTime();
            
            flight.departureAirport = m.group(4);
            flight.arrivalAirport = m.group(7);
            
            Log.d(TAG, flight.toString());
            
            CalEvent calEvent = flight.toCalEvent();
            calEvent.sourceSms = sms;
            results.add(calEvent);
        }
        return true;
    }
    
    public static class FlightInfo {
        public String passengerName;
        public String flightNumber;
        public Date departureDate;
        public Date arrivalDate;
        public String departureAirport;
        public String arrivalAirport;
        public String itineraryId;
        
        public CalEvent toCalEvent() {
            CalEvent event = new CalEvent();
            
            event.categories = "TRAVEL";
            event.description = toString();
            event.dtStamp = new Date();
            event.dtStart = departureDate;
            event.dtEnd = arrivalDate;
            event.location = departureAirport;
            event.summary = new StringBuffer()
                .append("航班").append(flightNumber)
                .append("于").append(departureDate)
                .append("从").append(departureAirport)
                .append("前往").append(arrivalAirport)
                .toString();
            
            return event;
        }
        
        @Override
        public String toString() {
            return new StringBuffer()
                .append("passengerName:").append(passengerName).append("\n")
                .append("flightNumber:").append(flightNumber).append("\n")
                .append("departureDate:").append(departureDate).append("\n")
                .append("arrivalDate:").append(arrivalDate).append("\n")
                .append("departureAirport:").append(departureAirport).append("\n")
                .append("arrivalAirport:").append(arrivalAirport).append("\n")
                .append("itineraryId:").append(itineraryId).append("\n")
                .toString();
        }
    }
}
